import BaseMctApi from "@/framework/infra/base/BaseMctApi";

class GeoAreaApi extends BaseMctApi {
  constructor() {
    super('geo/area')
  }

  list(param) {
    return super.list(param)
  }

  letterGroupedList(param) {
    return this.list(param).then(data => {
      if (!data.length) {
        return []
      }
      data = data.sort((a, b) => a.firstLetter < b.firstLetter ? -1 : (a.firstLetter === b.firstLetter ? 0 : 1))
      // console.log(data)
      const areaMap = data.reduce((r, a) => {
        r[a.firstLetter] = r[a.firstLetter] || []
        r[a.firstLetter].push(a)
        return r
      }, {})
      const colNum = 9
      const result = []
      const resultKeys = []
      let row = []
      let keyRow = []
      result.push(row)
      resultKeys.push(keyRow)
      Object.keys(areaMap).forEach(key => {
        const areaList = areaMap[key]
        if (row.length + areaList.length > colNum) {
          row = []
          keyRow = []
          result.push(row)
          resultKeys.push(keyRow)
        }
        keyRow.push(key)
        row.push(...areaList)
      })
      return result.map((el, idx) => {
        return {
          keys: resultKeys[idx].join(''),
          values: el
        }
      })
    })
  }
}

export const geoAreaApi = new GeoAreaApi()
